/**   
 *    
 * 项目名称：SmartKungFuService   
 * 类名称：ProjectDetailServlet   
 * 类描述：  我的活动接口 
 * 创建人：zhanghl   
 * 创建时间：2016年9月27日 下午4:34:25   
 * 修改人：zhanghl   
 * 修改时间：2016年9月27日 下午4:34:25   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.servlet;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.ProjectDetailReqPara;
import com.lst.entity.response.ProjectDetailResPara;
import com.lst.model.MstOrder;
import com.lst.model.OrderDetail;
import com.lst.model.ProjectDetail;
import com.lst.service.MstOrderService;
import com.lst.service.OrderDetailService;
import com.lst.service.ProjectDetailService;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: ProjectDetailServlet
 * @Description: 我的活动接口
 * @author zhanghl
 * @date 2016年9月27日 下午4:34:25
 *
 */
public class ProjectDetailServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	private ProjectDetailService projectDetailService = ctx.getBean(ProjectDetailService.class); 
	
	private MstOrderService mstOrderService = ctx.getBean(MstOrderService.class);

	private OrderDetailService orderDetailService = ctx.getBean(OrderDetailService.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		ProjectDetailResPara resPara = new ProjectDetailResPara();

		try {
			ProjectDetailReqPara reqPara = getReqPara(request);

			if(isCheckField(reqPara,resPara)){
				Integer clientid = Integer.valueOf(reqPara.getUserid());
				Integer page = Integer.valueOf(reqPara.getPage());
				Integer pagesize = Integer.valueOf(reqPara.getPagesize());

				Map<String, Object> pdMap = new HashMap<String, Object>();

				pdMap.put("enabled", true);
				pdMap.put("isDeleted", false);
				pdMap.put("clientid", clientid);
				pdMap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_PRO);
				pdMap.put("orderByClause", "o.updatedate desc");

				PageBounds pageBounds = new PageBounds(page , pagesize);

				List<ProjectDetail> pdlist = projectDetailService.queryList(pdMap,pageBounds);	

				PageBounds pagebounds = new PageBounds();				

				if(pdlist.isEmpty()){
					resPara.setPdlist(pdlist);
					resPara.setCode(CommCode.M_Y000000);
					resPara.setMessage(CommCode.M_Y000001);
				}else{
					List<ProjectDetail> plist = new ArrayList<ProjectDetail>();

					for(ProjectDetail p:pdlist){

						pdMap.put("orderid", p.getO().getId());

						List<ProjectDetail> prolist = projectDetailService.queryByList(pdMap,pagebounds);

						if(!prolist.isEmpty()){

							String starttime = StringUtils.isEmpty(prolist.get(0).getPi().getStartdate()) ? null : DateUtil.getFormatTime(prolist.get(0).getPi().getStartdate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
							String endtime = StringUtils.isEmpty(prolist.get(0).getPi().getEnddate()) ? null : DateUtil.getFormatTime(prolist.get(0).getPi().getEnddate(), DateUtil.ALL_DATETIME_SEPARATOR_SPOT);
							prolist.get(0).getPi().setStarttime(starttime);			
							prolist.get(0).getPi().setEndtime(endtime);
							
							//获取剩余人数
							Map<String, Object> momap = new HashMap<String, Object>();

							momap.put("enabled", true);
							momap.put("isDeleted", false);
							momap.put("actid", prolist.get(0).getPi().getId());	
							momap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_PRO);

							List<MstOrder> moList =  mstOrderService.queryByList(momap, pagebounds);

							Integer countnum = 0;

							for(MstOrder m : moList){

								momap.clear();
								momap.put("enabled", true);
								momap.put("isDeleted", false);
								momap.put("orderid", m.getId());	

								List<OrderDetail> odlist = orderDetailService.queryByList(momap, pagebounds);

								if(CommCode.SYSTEM_ORDER_STATUS_WAIT.equals(odlist.get(0).getOrderstatus())){
									countnum += m.getNum() == null ? 0 : m.getNum();
								}
							}

							Integer leavenum = prolist.get(0).getPi().getReserved1() - countnum;

							if(leavenum>=0){
								prolist.get(0).getPi().setLeavenum(leavenum);
							}else{
								prolist.get(0).getPi().setLeavenum(0);
							}

							//隐藏手机号
							if(!StringUtils.isEmpty(prolist.get(0).getO().getPhoneno())){
								String clientphonone = prolist.get(0).getO().getPhoneno().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
								prolist.get(0).getO().setClientphonone(clientphonone);
							}

							//倒计时
							if(!StringUtils.isEmpty(prolist.get(0).getO().getScheid())){

								String choose = prolist.get(0).getO().getScheid();							

								String[] temp = choose.split(" ");	

								if(temp[0] != null){

									Date start = DateUtil.parse(temp[0]);										

									Date date = new Date();
									
									Date startdate = DateUtil.getFormatDate(start,DateUtil.ALL_DATE_HORIZONTAL);

									Date  currentDate = DateUtil.getFormatDate(date, DateUtil.ALL_DATE_HORIZONTAL);

									int countdown = (int)((startdate.getTime()-currentDate.getTime())/86400000);

									if(countdown>0){
										prolist.get(0).getPi().setCountdown(countdown);
									}else {
										prolist.get(0).getPi().setCountdown(0);
									}

								}
							}

							plist.add(prolist.get(0));
						}

					}
					resPara.setPdlist(plist);
					resPara.setCode(CommCode.M_Y000000);
					resPara.setMessage(CommCode.M_Y000001);										
				}
			}

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);

			logger.info("ProjectDetailServlet jsonResult: " + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end: " + DateUtil.calLastedTime(startDate));

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public ProjectDetailReqPara getReqPara(HttpServletRequest request) {

		ProjectDetailReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new ProjectDetailReqPara());

			reqPara = (ProjectDetailReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");		
			String page = request.getParameter("page");
			String pagesize = request.getParameter("pagesize");

			logger.info("reqPara userid: " + userid);			
			logger.info("reqPara page: " + page);
			logger.info("reqPara pagesize: " + pagesize);

			reqPara.setUserid(userid);			
			reqPara.setPage(page);
			reqPara.setPagesize(pagesize);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		ProjectDetailReqPara pdReqPara = (ProjectDetailReqPara) reqPara;
		ProjectDetailResPara pdResPara = (ProjectDetailResPara) resPara;

		if (StringUtils.isEmpty(pdReqPara.getUserid())) {
			pdResPara.setCode(CommCode.M_A000000);
			pdResPara.setMessage(CommCode.M_P000002);
		} else if (StringUtils.isEmpty(pdReqPara.getPage())){
			pdResPara.setCode(CommCode.M_A000000);
			pdResPara.setMessage(CommCode.M_P000009);
		} else if (StringUtils.isEmpty(pdReqPara.getPagesize())){
			pdResPara.setCode(CommCode.M_A000000);
			pdResPara.setMessage(CommCode.M_P000010);
		} else {
			flag = true;
		}
		return  flag;
	}
}
